package com.servicesystem.servicesystem.untis.token;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SecurityException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import java.util.Date;

@Component
public class GenerateTokenUtils implements InitializingBean {

    //private Date date = new Date(System.currentTimeMillis() + (1 * 60 * 1000));
    Date date = new Date(System.currentTimeMillis() + (60 * 60 * 1000 * 12));
    private final static String key = "HelloWord";
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;

    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(key).parseClaimsJws(token);
            return true;
        } catch (SecurityException | MalformedJwtException | ExpiredJwtException | UnsupportedJwtException | IllegalArgumentException e) {
            //e.printStackTrace();
            throw new CustomException("Token不可以使用");
        }
    }

    public String generateToken(Authentication user) {

        JwtBuilder builder = Jwts.builder()
                .setSubject(user.getName())
                .setIssuedAt(new Date())
                .signWith(signatureAlgorithm, key)
                .setExpiration(new Date(System.currentTimeMillis() + (60 * 60 * 1000 * 12)));
        return builder.compact();
    }

    public String parseToken(String token) {
        try {
            Claims body = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
            return body.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getTokenByHead(ServletRequest servletRequest) {
        return servletRequest.getAttribute("token").toString();
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
